package com.csr;

import java.io.IOException;
import java.net.UnknownHostException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List; 
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject; 
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputType;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class AddBalanceActivity extends Activity implements OnClickListener
{
	
	TextView tv_shopName; 
	ResellerInfo agentInfo=AppData.agentInfo;
	Handler handler=new Handler();
	MD5Generator md5Generator=new MD5Generator();
	HttpClient httpclient;
	HttpPost httppost = new HttpPost(AppData.hostURL+"/WebService/iTopUp/csrapp.php");
	ProgressDialog pd=null;
	private EditText etAmount,etTransactionPin,etDescription;
	private Button btnOk;
	JSONObject jsonObject;
	String newBalance;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_balance_activity);
		etAmount=(EditText)findViewById(R.id.etAmount);
		etAmount.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_DECIMAL);
		etTransactionPin=(EditText)findViewById(R.id.etTransactionPin);
		etDescription=(EditText)findViewById(R.id.etDiscription);
		btnOk=(Button)findViewById(R.id.btn_ok); 
		btnOk.setOnClickListener(this); 
	}
	public void onClick(View v) 
	{
		if (v == btnOk)
		{
			try
			{
				String msg=validateInput();
				if(msg.equalsIgnoreCase("success"))
				{
					new AddBalanceDialog(AddBalanceActivity.this).show();
				}
				else
				{
					Toast.makeText(AddBalanceActivity.this,msg,Toast.LENGTH_SHORT).show();
				}
				
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}
		 
		 
		
	}
	
	private String validateInput() 
	{
		
		try
		{
			if(!(etAmount.getText().toString().trim().length()>0))
			{
				return "Please Enter Amount";
			}
			if(!(etDescription.getText().toString().trim().length()>0))
			{
				return "Please Enter Description";
			}
			if(etTransactionPin.getText().toString().trim().length()>0)
			{
				if(!AppData.getUserInfo().getTransactionPassword().equals(md5Generator.MD5(etTransactionPin.getText().toString())))
				{
					return "Invalid Transaction PIn";
				}
				else
				{
					return "success";
				}
			}
			else
			{
				return "Please Enter Transaction Pin";
				
			}
			
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return null;
		}
		
	}

	private class AddBalanceDialog extends Dialog implements OnClickListener
	 {
		private Context context; 
		private Button btnOkConfirmation,btnCancelConfirmation;
		private Double amount;
		private TextView tvConfirmationText,tvDialogHeader;
		
		public AddBalanceDialog(Context context) 
		{
			super(context);
			this.context=context;
			requestWindowFeature(Window.FEATURE_NO_TITLE);
			setContentView(R.layout.confirmation_layout);
			tvConfirmationText=(TextView)findViewById(R.id.tvConfirmationText); 
			btnOkConfirmation=(Button)findViewById(R.id.btn_Ok_confirmation);
			btnCancelConfirmation=(Button)findViewById(R.id.btn_Continue_confirmation);
			tvConfirmationText.setText("Tuma "+etAmount.getText().toString() +" Tshs kwenda namba "+agentInfo.getPhone1()+".");
			btnOkConfirmation.setOnClickListener(this);
			btnCancelConfirmation.setOnClickListener(this);
		}
		
		public void onClick(View v) 
		{
			if(v==btnOkConfirmation)
			{
				dismiss();		 
				amount =Double.parseDouble(etAmount.getText().toString())*100;
				new Thread(addBalance, "Add Balance").start();
				pd=ProgressDialog.show(AddBalanceActivity.this,"please wait.",null);
				pd.setContentView(R.layout.progress);
				  
			}
			else if(v==btnCancelConfirmation)
			{
				dismiss();
			}	
			
		}
		double roundTwoDecimals(double d) 
		{
	        DecimalFormat twoDForm = new DecimalFormat("#.##");
	        return Double.valueOf(twoDForm.format(d));
		}
		private Runnable addBalance=new Runnable()
		{
			
			public void run()
			{
				try
				{
					httpclient = new DefaultHttpClient();
					String checksumString=
										AppData.getUserInfo().getLoginID()+"|"+
										agentInfo.getPhone1()+"|"+
										amount+"|"+etDescription.getText().toString()+"|"+
										AppData.getUserInfo().getpublickey();
					System.out.println("Check sum string===>"+checksumString);
					String finalChecksum = md5Generator.MD5(md5Generator.SHA1(checksumString));
					System.out.println("Final Checksum:"+finalChecksum);
					try 
					{      
						List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
						nameValuePairs.add(new BasicNameValuePair("function", "BalanceTransfer"));
					    nameValuePairs.add(new BasicNameValuePair("LoginId", AppData.getUserInfo().getLoginID()));
					    nameValuePairs.add(new BasicNameValuePair("Phone1", agentInfo.getPhone1()));
					    nameValuePairs.add(new BasicNameValuePair("Amount",Double.toString(amount))); 
					    nameValuePairs.add(new BasicNameValuePair("Description",etDescription.getText().toString()));
					    nameValuePairs.add(new BasicNameValuePair("Checksum",finalChecksum));
					    
					    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
					    
					    ResponseHandler<String> responseHandler = new BasicResponseHandler();
					    
						String response = httpclient.execute(httppost,responseHandler);
						System.out.println("Response:"+response);
					    
						jsonObject=new JSONObject(response);
					
						
						  if(jsonObject.getString("ResponseCode").equals("000"))
			              {
								newBalance=jsonObject.getString("Balance");
								handler.post(new Runnable()
								{ 
									public void run() 
									{
//										try 
//										{
//											//tvBalance.setText(""+roundTwoDecimals(Double.parseDouble(jsonObject.getString("Balance"))/100));
//										} 
//										catch (JSONException e) 
//										{
//											e.printStackTrace();
//										}
										
										pd.dismiss();
										AppData.agentInfo.setBalance(""+Double.parseDouble(newBalance)/100);
										Toast.makeText(AddBalanceActivity.this,"Balance Transfered Successfully",Toast.LENGTH_LONG).show();
										etTransactionPin.setText("");
										etAmount.setText("");
										etDescription.setText("");
									}
								});
							  	 
			              }
						  else
						  {
							  handler.post(new Runnable()
			            	  {
								
								public void run() 
								{
									
									pd.dismiss();
									try 
									{
										Toast.makeText(AddBalanceActivity.this,jsonObject.getString("ResponseDescription"),Toast.LENGTH_SHORT).show();
										
									}
									catch (JSONException e) 
									{
										e.printStackTrace();
									}
								}
							});
							  
						  }
					}
					catch (final JSONException e)
					{
						handler.post(new Runnable()
						{
							
							public void run() 
							{
								// TODO Auto-generated method stub
								pd.dismiss();
								Toast.makeText(AddBalanceActivity.this,e.getMessage(),Toast.LENGTH_LONG).show(); 
							}
						});
					}
					catch(UnknownHostException e)
					{
						
						handler.post(new Runnable()
						{
							
							public void run() 
							{
								// TODO Auto-generated method stub
								pd.dismiss();
								Toast.makeText(AddBalanceActivity.this,getString(R.string.conn_msg),Toast.LENGTH_LONG).show(); 
							}
						});
						 
					}
					catch (final ClientProtocolException e) 
					{
				        // TODO Auto-generated catch block
							handler.post(new Runnable()
							{
								
								public void run() 
								{
									// TODO Auto-generated method stub
									pd.dismiss();
									Toast.makeText(AddBalanceActivity.this,getString(R.string.conn_msg),Toast.LENGTH_LONG).show(); 
								}
							});
							 
				    }
					
					catch (final IOException e) 
					{
							handler.post(new Runnable()
							{
								
								public void run() 
								{
									// TODO Auto-generated method stub
									pd.dismiss();
									Toast.makeText(AddBalanceActivity.this, e.getMessage(),Toast.LENGTH_LONG).show();
								}
							}); 
				    }  
				}
				
				catch(Exception e)
				{
					e.printStackTrace();
				}
				
			}
		};
			
	}//addbalance dialog
	 
}
